package com.birdboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;

/**
 * 该线程的任务是与指定客户端完成HTTP交互
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public  ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        // 1、解析请求
        // 1.1 解析请求行
        try {

            String line = readLine();
            System.out.println("请求行："+line);
            // 将请求行中的请求方式，抽象路径，协议版本分别解析出来
            String method;
            String uri;
            String protocol;
            String[] data = line.split("\\s");
            method = data[0];
            uri = data[1];
            protocol = data[2];
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);

            // 1.2解析消息头
            HashMap<String,String> headers = new HashMap();

            while (true) {
                line = readLine();
                if (line.isEmpty()){
                    break;
                }
                System.out.println("消息头："+line);
                data = line.split(":\\s");
                headers.put(data[0],data[1]);

            }
            System.out.println("headers:"+headers);
            headers.forEach((k,v)-> System.out.println(k+"=="+v));
            // 2、处理请求



            // 3、发送响应




        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //遵循Http协议要求，一问一答后关闭连接，finally里面的代码每次运行后都要运行
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 将v2版本的run方法里测试读取一行字符串的操作封装成一个方法
    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();// 保存拼接后的字符串
        char cur,pre = 'a';// cur表示本次读取的字符，pre表示上次读取的字符
        while ((d=in.read())!=-1) {
            cur = (char) d;
            if (pre==13 && cur==10){
                break;
            }
            builder.append(cur);
            pre=cur;
        }
        String line =  builder.toString().trim();
        return line;
    }
}
